const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');


const query = require("./util/db.js")
const R = require("./util/resultJson.js")

const indexRouter = require('./routes/index');
const userinfoRouter = require('./routes/userinfo');
const uploadRouter = require('./routes/upload');
const storeRouter = require('./routes/store');
const supplierRouter = require('./routes/supplier');
const goodsRouter = require('./routes/goods');
const applyRouter = require('./routes/apply');
const recordsRouter = require('./routes/records');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

/*
* 默认情况下所有的请求都会进入app这个文件，这里设置的是白名单
* */
app.all("/*",function (req,res,next) {
  const whiteSheet = ["/","/login","/nologin"];
  if(whiteSheet.includes(req.url)){
    next();
  }else{
    /*获取token*/
    const token = req.cookies.token;
    let sql = "select u.*,t.expire,t.id tid from user_login t left join userinfo u on t.user_id = u.id where t.token = ?";
    query(sql,[token]).then(data=>{
      if(data.length>0){
        const tokenInfo = data[0];
        if(new Date().getTime() < tokenInfo.expire.getTime()){
          req.loginInfo = tokenInfo
          next();
        }else{
          if(req.xhr){
            res.json(R.error("未登录，请先登录！",401))
          }else{
            res.redirect("/nologin")/*重定向*/
          }
        }
      }else{
        if(req.xhr){
          res.json(R.error("未登录，请先登录！",401))
        }else{
          res.redirect("/nologin")/*重定向*/
        }
      }
    })
  }
})

app.use('/', indexRouter);
app.use('/userinfo', userinfoRouter);
app.use('/upload', uploadRouter);
app.use('/store', storeRouter);
app.use('/supplier', supplierRouter);
app.use('/goods', goodsRouter);
app.use('/apply', applyRouter);
app.use('/records', recordsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
